package com.changhong.framework.sdfs.namenode.server.nio;

import com.alibaba.fastjson.JSONObject;
import com.changhong.framework.sdfs.namenode.server.constant.MemoryBufferType;
import com.changhong.framework.sdfs.namenode.server.constant.NameNodeConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;

/**
 * @author summer
 */
public class MemoryBuffer {

    private static final Logger logger = LoggerFactory.getLogger(MemoryBuffer.class);

    private final ByteArrayOutputStream memoryBufferData;


    public MemoryBuffer(){
        this(MemoryBufferType.MEMORY_BUFFER_SIZE);
    }

    public MemoryBuffer(int bufferSize){
        memoryBufferData=new ByteArrayOutputStream(bufferSize);
    }

    public int getCurrentBufferSize(){
        return memoryBufferData.size();
    }

    public boolean write(EditLog log) throws Exception{
        memoryBufferData.write(formatJsonString(log).getBytes());
        return true;
    }

    private String formatJsonString(EditLog log){
        return JSONObject.toJSONString(log) + NameNodeConstant.SPIT_SYMBOL;
    }

    public void clear(){
        memoryBufferData.reset();
    }
    /**
     * 获取内存缓冲区当前的数据
     * @return
     */
    public byte[] getBufferData() {
        return memoryBufferData.toByteArray();
    }

}
